package com.windx.exception;

import com.windx.common.ApiResult;
import com.windx.common.ResultCode;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;

/**
 * @author 倚栏听风
 * @date 2023/4/16 15:20
 */
@Component
public class ExceptionHandler implements Filter {
    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        try {
            chain.doFilter(ctx);
        } catch (Throwable error) {
            //自定义异常处理
            if (error instanceof ApiException) {
                ResultCode code = ((ApiException) error).getCode();
                ApiResult<Object> result = ApiResult.failed(error.getMessage());
                if (code != null) {
                    result.setCode(code.getCode());
                }
                ctx.render(result);
            } else {
                ctx.render(ApiResult.failed(error.getMessage()));
            }
        }
    }
}
